#/usr/bin/python
# coding: utf8

import time
#from  PAM30 import PAM30
import PAM30
import sys
import win32api
import win32con
import win32gui
import random
import ConfigParser
import hashlib
import logging
import datetime

reload(sys)
sys.setdefaultencoding("utf-8")


def logme(info, file='searchlog.txt'):
    '''
    记录log文件
    '''
    logger=logging.getLogger()
    logger.setLevel(logging.NOTSET)
    handler=logging.FileHandler(file)
    logger.addHandler(handler)
    logger.info(info)


def logit(content):
    '''
    另一种log记录函数
    '''
    file = open('searchlog.txt', 'a')
    try:
        timestr = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')+': '
        file.write(timestr+content+'\r\n')
    finally:
        file.close()


def makesn(strs):
    '''
    生成sn
    '''
    x = hashlib.sha224((hashlib.md5(strs)).hexdigest()+'jhfaixiaobao')
    #print x.hexdigest()
    return x.hexdigest()


def checksn(taobaoid, sn):
    '''
    检查sn是否正常
    '''
    if(sn == makesn(taobaoid)):
        #print 'OK'
        return True
    else:
        #print 'Error'
        return False


def jumpIEtab():
    '''
    跳转ctl+Tab,ie8的跳到下一个窗口的快捷键
    '''
    win32api.keybd_event(17, 0, 0, 0)#ctrl
    win32api.keybd_event(9, 0, 0, 0)#tab
    win32api.keybd_event(9, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)


def pageDown():
    '''
    单纯按pagedown键，随机停留1-5秒
    '''
    win32api.keybd_event(34, 0, 0, 0)#pagedown
    time.sleep(0.5)
    win32api.keybd_event(34, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 5))


def pageUp():
    '''
    按pageUp键，随机停留1-3秒
    '''
    win32api.keybd_event(33, 0, 0, 0)#pageup
    time.sleep(0.5)
    win32api.keybd_event(33, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 3))


def endPage():
    '''
    end键，到页面底部
    '''
    win32api.keybd_event(35, 0, 0, 0)#edn
    time.sleep(0.5)
    win32api.keybd_event(35, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 3))


def homePage():
    '''
    home键，到页面顶部
    '''
    win32api.keybd_event(36, 0, 0, 0)#home
    time.sleep(0.5)
    win32api.keybd_event(36, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 3))


def clickBar():
    '''
    点击商品页面的信用详情页面
    '''
    bar = ie.findElement('ul', 'id', 'J_TabBar')
    bars = ie.getElementChildren(bar)
    ebar = ie.getElementChildren(bars[2])
    ie.clickElement(ebar[0])


def pageView():
    '''
    针对当前商品IE页面翻页，然后回到页面头部，点击信用页面
    再翻页浏览，再回到商品页面头部
    '''
    win32api.keybd_event(122, 0, 0, 0)#f11
    win32api.keybd_event(122, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 7))
    t = random.randint(7, 20)
    i= 0
    while(i<t):
        pageDown()
        if(i>10 and i<16):
            pageUp()
        i = i+1
    endPage()
    clickBar()
    j = 0
    while(j<10):
        pageDown()
        time.sleep(random.randint(1, 7))
    homePage()


def pageViewL():
    '''
    针对当前IE页面翻页，随机浏览然后回到页面头部
    '''
    win32api.keybd_event(122, 0, 0, 0)#f11
    win32api.keybd_event(122, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 6))
    t = random.randint(5, 10)
    i= 0
    while(i<t):
        pageDown()
        if(i>3 and i<7):
            pageUp()
        i = i+1
    endPage()
    homePage()


def favoItem():
    '''
    点击收藏按钮，默认是登录状态
    '''
    bar = ie.findElement('span', 'innerText', u'收藏宝贝')
    ie.clickElement(bar)
    time.sleep(1)
    x = ie.findElement('a', 'innerText', 'X')
    ie.clickElement(x)


def setRegValue(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv==value):
            return True
        else:
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
            win32api.RegCloseKey(key)
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def ordd(str):
    '''
    解决键盘码不对应问题,不知道别的电脑有没有这个问题
    '''
    t = ord(str)
    #65到90是A到Z
    if(t>90):
        return t-32
    else:
        return t


def typeme(passw):
    '''
    模拟人工输入,自动输入参数字符串到焦点窗口
    '''
    psht = len(passw)
    for j in range(psht):
        win32api.keybd_event(ordd(passw[j]), 0, 0, 0)
        time.sleep(0.5)
        win32api.keybd_event(ordd(passw[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.5)


def lgTaobao(username, userpass):
    '''
    使用指定用户名密码（在IE）登录淘宝
    '''
    #lgurl = 'http://i.taobao.com/my_taobao.htm?spm=a1z0e.3.217351.2.9fe82b&scm=1012.1.30.0'
    lgurl = 'https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fspm%3Da1z0e.3.217351.2.9fe82b%26scm%3D1012.1.30.0'
    ie.navigate(lgurl)
    ie.setTextBox('TPL_username', username.decode('utf-8'))
    ie.setCheckBox('J_SafeLoginCheck', 0)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    #ie.clickButton('J_SubmitStatic')
    ie.clickElement(bt)
    ie.setTextBox('TPL_password', userpass)
    typeme(userpass)
    time.sleep(0.5)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    ie.clickElement(bt)
    if(ie.findText(username)):
        return True
    else:
        return False


def exitTaobao(username):
    '''
    退出当前登录状态（使用给定帐号退出）
    '''
    isLogin = ie.findText(username)
    if(isLogin):
        #ie.clickLink('退出')
        ie.clickHiddenLink('J_Logout')
        isLogout = not(ie.findText(username))
        if(isLogout):
            return True
        else:
            return False
    else:
        win32gui.MessageBox(0, '未登录！'.decode('utf-8'), 'Notice!', 0)


def clickColor(s1):
    '''
    点击商品的颜色等选项，参数为选项文字
    最多三个选项
    '''
    c1 = ie.findElement('span', 'innerText', s1)
    f = ie.clickElement(c1)
    return f


def addItem2cart():
    '''
    拍下某个宝贝，加入购物车
    '''
    isAddok = ie.clickLink('加入购物车')
    if(isAddok):
        time.sleep(1)
        ie.clickLink('<span>关闭</span>')
        return True
    else:
        win32gui.MessageBox(0, '设置数量失败！'.decode('utf-8'), 'Notice!', 0)


def changeWin(itemname):
    '''
    找到淘宝id，然后点击商品链接,跳到对应tab页
    #print ("find "+taoid.encode('gbk'))
    '''
    pdt = ie.findElement('a', 'title', itemname)
    #IE8要设置总是允许来自s.taobao.com的弹出窗口
    ie.clickElement(pdt)
    time.sleep(2)
    consis = str(pdt).find('tmall')
    if(consis == -1):
        ie.changeWindow(itemname+'-淘宝网')
    else:
        ie.changeWindow(itemname+'-tmall.com天猫')
    #跳转ctl+Tab,ie8的跳到下一个窗口的快捷键
    jumpIEtab()
    return True


def searchWd(sword, itemid, itemname, mtaoid, maxPage):
    '''
    根据提供的关键词进行搜索，遍历1-10页寻找商品id
    找到后点击商品页面，切换界面到新IE窗口
    '''
    print mtaoid
    ie.navigate('http://www.taobao.com')
    ie.setTextBox('q', sword.encode('gbk'))
    ie.submitForm('search')
    #ie.clickButton('搜索')
    time.sleep(2)
    isFindItem = ie.findText(itemid)
    isFindt = ie.findText(mtaoid)
    page = 1
    #pageViewL()
    if(isFindItem and isFindt):
        changeWin(itemname)
        logit('Find on page '+str(page)+' '+itemname)
    else:
        while(page<maxPage):
            print 'Not Find :'+itemid
            next = ie.findElement('span', 'innerText', '下一页')
            if(next):
                page = page + 1
                ie.clickLink(next)
                logit('     进入下一页 '+str(page))
            else:
                break
            #pageViewL()
            time.sleep(1)
            isFind = ie.findText(itemid)
            isFindt = ie.findText(mtaoid)
            if(isFind and isFindt):
                print isFind
                print itemid
                logit('Find on page '+str(page)+' '+itemname)
                changeWin(itemname)
                return True
            else:
                logit('Not find,go on next page or jump to next word ...')
        if(page>maxPage):
            #win32gui.MessageBox(0, '商品未找到！'.decode('utf-8'), 'Notice!', 0)
            logit('搜索词在'+str(maxPage)+'页中都未找到...')
            return False

'''
主函数：单帐号读取配置文件，搜索单个商品的多关键词，模拟浏览收藏
1.读取配置文件，获得帐号和使用密码，如果不符合，则退出，否则自动打开淘宝登录
2.读取商品数量
3.按照数量循环获取关键词、商品id和名称

4.模拟人工搜索每个关键词，自动翻页寻找
5.找到商品后点击商品名称链接，打开商品
6.模拟人工浏览商品
7.收藏商品

8.切换ip，进入下个商品循环
'''
config = ConfigParser.ConfigParser()
config.read('search.ini')
taobaoid = config.get("global", "taobaoid")
mtaoid = config.get("global", "mtaobaoid")
sn = config.get("global", "sn")
maxPage = config.getint("global", "maxPage")
if(checksn(taobaoid, sn)):
    #sn正确,#获取配置文件，检查sn,组装参数
    loginpass = config.get("global", "loginpass")
    paypass = config.get("global", "paypass")
    #允许淘宝的弹出窗口
    keystr = 'SOFTWARE\\Microsoft\\Internet Explorer\\New Windows\\Allow'
    setRegValue(keystr, 's.taobao.com', '0')
    itemcount = config.getint("global", "itemcount")
    items = range(itemcount)
    itemnames = range(itemcount)
    searchs = range(itemcount*3)
    ie= PAM30.PAMIE()
    #每个商品3个搜索词
    for i in range(itemcount):
        items[i] = 'id='+((config.get("items", "item"+str(i+1))).split('id='))[1]
        itemnames[i] = config.get("items", "name"+str(i+1))
        print('Goods'+str(i+1)+' :'+items[i]+','+itemnames[i].encode('gbk'))
        for j in range(3):#每个商品3个搜索关键词
            k = (i*3)+1
            searchs[j+k-1] = config.get("searchs", "sword"+str(j+k))
            #logme(str(j+k)+searchs[j].encode('gbk'))
        #print (searchs[k]).encode('gbk')
    x = 0
    y = len(searchs)
    while(x<y):
        #print searchs[x-1]
        v = (x)/3
        pname = ' '+items[(x)/3]+','+itemnames[(x)/3]
        logit('\r\n \r\n 搜索词'+str(x+1)+':'+searchs[x]+'开始搜索...')
        logit('         商品'+str(v+1)+pname)
        x = x + 1
        f = searchWd(searchs[x], items[x/3], itemnames[x/3], mtaoid, maxPage)
        if(f):
            logit('Find: '+items[(x)/3])
            win32api.Beep(3000, 2000)
        else:
            #logit('Not Find '+items[(x)/3])
            pass
    win32api.Beep(200, 300)
    time.sleep(0.8)
    win32api.Beep(200, 300)
    time.sleep(0.8)
    win32api.Beep(200, 300)

else:
    #sn错误
    print '你的帐号和sn不匹配，请联系客服确认是否正确'
    win32gui.MessageBox(0, 'SN错误，请联系客服！'.decode('utf-8'), 'Notice!', 0)
